package com.neusoft.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bo.CreditBO;
import com.neusoft.mapper.CreditMapper;
import com.neusoft.mapper.OrdersMapper;
import com.neusoft.po.Credit;
import com.neusoft.po.Orders;
import com.neusoft.service.CreditService;
import com.neusoft.util.CommonUtil;


@Service
public class CreditServiceImpl implements CreditService{
	@Autowired
	OrdersMapper ordersMapper;
	@Autowired
	CreditMapper creditMapper;
	
	//获取可用积分
	public int getUsableCredit(String userId) {
//		Integer result=null;
//		result=creditMapper.getCredit(userId, CommonUtil.getCurrentDate());
//		if(result==null) {
//			return 0;
//		}
		//加入合法性检查
		return creditMapper.getUsableCredit(userId, CommonUtil.getCurrentDate());
	}
	
	public List<Credit> getCreditTransaction(String userId) {
		return creditMapper.getCreditTransaction(userId);
	}
	
	public int ordersAddCredit(Orders order) {
		//BO处理业务
		//获取订单金额,并计算对应积分
		CreditBO creditBO = new CreditBO();
		int addAmount = creditBO.ordersAddCreditRule(order);
		
		//增加积分
		Credit credit = new Credit();
		credit.setUserId(order.getUserId());
		credit.setAmount(addAmount);
		credit.setLeftAmount(addAmount);
		credit.setType(1);
		credit.setStartTime(order.getOrderDate());
		credit.setEndTime(getEndTime(order.getOrderDate()));
		return creditMapper.saveCredit(credit);
	}
	
	//积分有效期的规则
	public String getEndTime(String startTime) {
		//设定的规则：积分有效期为一个月
		return CommonUtil.getAfterMonth(startTime, 1);
	}

		//根据可用积分获取用户可抵扣数额
	@Override
	public Double ordersGetDiscount(String userId) {
		int credit = creditMapper.getUsableCredit(userId, CommonUtil.getCurrentDate());
		//这里是积分抵扣规则
		CreditBO creditBO = new CreditBO();
		Double discount = creditBO.ordersGetDiscount(credit, 100);
		return discount;
	}

	//传入已支付订单，使用积分抵扣
	@Override
	public int ordersUseDiscount(Orders order) {
		//1.创建使用流水
		String nowTime = CommonUtil.getCurrentDate();
		int amount = creditMapper.getUsableCredit(order.getUserId(), nowTime);
		Credit credit = new Credit();
		credit.setUserId(order.getUserId());
		credit.setAmount(amount);
		credit.setLeftAmount(0);//消费积分，剩余设置为0
		credit.setType(2);
		credit.setStartTime(nowTime);
		//credit.setEndTime(getEndTime(order.getOrderDate()));
		creditMapper.saveCredit(credit);
		//2.减少left
		return creditMapper.zeroCredit(order.getUserId(), nowTime);
	}
	
	
}
